<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="24">
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">机柜名称：</span>
        <el-input placeholder="请输入名称" v-model="queryForm.query.name"
                  style="flex:1;"></el-input>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">公司：</span>
        <el-select clearable v-model="queryForm.query.compayid"
                   placeholder="请选择公司" style="flex:1;">
          <el-option v-for="item in companyList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">部门：</span>
        <el-select clearable v-model="queryForm.query.departmentid"
                   placeholder="请选择部门" style="flex:1;">
          <el-option v-for="item in serarch_departmentList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">机房：</span>
        <el-select clearable v-model="queryForm.query.computerroomid"
                   placeholder="请选择机房" style="flex:1;">
          <el-option v-for="item in serarch_roomList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col style="min-width: 9%;max-width:13%">
        <el-button type="hawkSearch" @click="search()">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="editCabinet()">创建机柜</el-button>
      </el-col>
    </el-row>
    <hawk-table :table-data="tableData" v-model="multipleSelection"
                :page="queryForm.page" :number=true :options="[
        { key: 'name', label: '名称' },
        { key: 'specifications', label: '规格', width:'70' },
        { key: 'companyName', label: '公司' },
        { key: 'departmentName', label: '部门' },
        { key: 'roomName', label: '机房' },
        { key: 'supplierName', label: '供应商' },
        { key: 'purchasedate', label: '采购日期' },
        { key: 'comfirmeddate', label: '过保日期' },
        { key: 'installdate', label: '安装日期' },
        { key: 'total', label: '总量', width:'60' },
        { key: 'princicalName', label: '负责人', width:'70' },
        { key: 'princicalTelphone', label: '联系电话' },
        { key: 'handle', label: '操作' }
      ]">
      <template #princicalTelphone="{ row }">
        <span>{{row.sysUser?row.sysUser.mobile:''}}</span>
      </template>
      <template #princicalName="{ row }">
        <span>{{row.sysUser?row.sysUser.nickName:''}}</span>
      </template>
      <template #supplierName="{ row }">
        <span>{{row.provider?row.provider.name:''}}</span>
      </template>
      <template #companyName="{ row }">
        <span>{{row.company?row.company.name:''}}</span>
      </template>
      <template #roomName="{ row }">
        <span>{{row.computerRoom?row.computerRoom.name:''}}</span>
      </template>
      <template #departmentName="{ row }">
        <span>{{row.department?row.department.name:''}}</span>
      </template>

      <template #purchasedate="{ row }">
        <span>{{transformDateFormat(row.purchasedate,'yyyy-MM-dd')}}</span>
      </template>
      <template #comfirmeddate="{ row }">
        <span>{{transformDateFormat(row.comfirmeddate,'yyyy-MM-dd')}}</span>
      </template>
      <template #installdate="{ row }">
        <span>{{transformDateFormat(row.installdate,'yyyy-MM-dd')}}</span>
      </template>
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="editCabinet(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="deleteCabinet(row)">删除</span>
      </template>
    </hawk-table>

    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="catchDelete()">批量删除</el-button>
        <!-- <el-button plain>导出</el-button> -->
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="formTitle" :visible.sync="addDialogVisible"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
               label-width="120px">
        <el-form-item label="机柜名称" prop="name">
          <el-input :readonly="formTitle == '查看机柜'" v-model="addForm.name">
          </el-input>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="addForm.specifications"></el-input>
        </el-form-item>
        <el-form-item label="公司" prop="compayid">
          <el-select clearable v-model="addForm.compayid" placeholder="请选择公司"
                     @change="checkName" style="flex:1;">
            <el-option v-for="item in companyList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departmentid">
          <el-select clearable v-model="addForm.departmentid"
                     placeholder="请选择部门" @change="checkName" style="flex:1;">
            <el-option v-for="item in departmentList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机房" prop="computerroomid">
          <el-select clearable v-model="addForm.computerroomid"
                     placeholder="请选择机房" @change="checkName">
            <el-option v-for="item in roomList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select clearable v-model="addForm.providerid"
                     placeholder="请选择供应商">
            <el-option v-for="item in supplierList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购日期" prop="purchasedate">
          <el-date-picker v-model="addForm.purchasedate" type="date"
                          placeholder="质保日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="质保年限" prop="qualitytime">
          <el-input v-model.number="addForm.qualitytime" placeholder="质保XX年">
          </el-input>
        </el-form-item>

        <el-form-item label="安装日期" prop="installdate">
          <el-date-picker v-model="addForm.installdate" type="date"
                          placeholder="安装日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="容量">
          <el-input v-model="addForm.total"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="sysuserid">
          <el-select clearable v-model="addForm.sysuserid" placeholder="请选择负责人">
            <el-option v-for="item in principalList" :key="item.id"
                       :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCabinet()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author  肖帅
 * @description 机柜视图容器
 * @api /cmdb-hshelf
 * @since 2021-10-12 15:30
 * @update
 * @modifier
 * @bug 无
 * @version v1.0.1
 */

import {
  getList,
  doDelete,
  doAdd,
  doEdit,
  isNameExists
} from '@/api/assets/list/cabinet'
import { getAll as getRoomList, queryComputerRoom } from '@/api/assets/list/computerRoom'
import { getAll as getSupplierList } from '@/api/assets/dictionaries/supplier'
import { getAllCompany as getCompanyList } from '@/api/assets/dictionaries/company'
import { getAll as getDepartmentList, getDepartByComId } from '@/api/assets/dictionaries/department'
import { getAll as getPrincipalList } from '@/api/system/user'
export default {
  data () {

    let inHaveName = async (rule, value, callback) => {

      console.log(1111);
      if (this.addForm.compayid == '' || this.addForm.departmentid == ''
        || this.addForm.computerroomid == '') {
        callback(new Error('请先选择公司、部门、机房'))
        return
      }
      console.log(2222);

      let ret = await isNameExists({
        companyId: this.addForm.compayid,
        deptId: this.addForm.departmentid,
        roomId: this.addForm.computerroomid,
        name: value,
      })
      console.log(ret);

      if (ret.code == 998) {
        callback()
      } else {
        callback(new Error('名称已经存在'))
      }

    }


    return {
      // 公司列表，页面和弹框共用
      companyList: [],
      // 所有供应商
      supplierList: [],

      //-------弹出框中的数据-----
      departmentList: [],
      roomList: [],
      principalList: [], // 机房管理员

      // ----页面搜索框的数据---------

      serarch_departmentList: [],
      serarch_roomList: [],
      serarch_principalList: [],


      formTitle: '添加机柜',
      addDialogVisible: false,
      multipleSelection: [],

      addForm: {
        qualitytime: '', // 质保时间 n 年
        comfirmeddate: '', // 过保年限，N 年
        compayid: '',
        computerroomid: '',
        departmentid: '',
        id: '', // 机柜ID
        installdate: '',
        name: '',  // 机柜名称
        phone: '',
        providerid: '',
        purchasedate: '',

        specifications: '', // 规格

        total: null,
        sysuserid: ''
      },

      addFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: inHaveName, trigger: 'blur' }
        ],
        compayid: [{ required: true, message: '请选择公司', trigger: 'change' },],
        departmentid: [{ required: true, message: '请选择部门', trigger: 'change' },],
        computerroomid: [{ required: true, message: '请选择机房', trigger: 'change' },],
        sysuserid: [{ required: true, message: '选择负责人', trigger: 'change' },],
        purchasedate: [{ required: true, message: '选择采购日期', trigger: 'change' },],
        qualitytime: [{ required: true, message: '选择质保年限', trigger: 'change' },],
        installdate: [{ required: true, message: '选择安装日期', trigger: 'change' },],



      },

      tableData: [],
      total: 0,

      queryForm: {
        query: {
          name: '', // 机柜名称
          compayid: '',
          departmentid: '',
          computerroomid: ''
        },
        page: {
          current: 1,
          size: 10
        }
      },

      isFirstEdit: false
    }
  },
  //监听属性 类似于data概念",
  computed: {
    cellStyle () {
      return {
        padding: '8px 0',
      }
    },
  },
  //监控data中的数据变化",
  watch: {
    "addForm.compayid": {
      async handler (newValue, oldValue) {
        // 根据公司，获得该公司的部门
        console.log(newValue,'---------被清空了---------');

           if (!newValue){
            // 清空 公司，部门
            this.addForm.departmentid = ''
            this.departmentList = []
            this.addForm.computerroomid = ''
            this.roomList = []
            this.addForm.sysuserid = ''
            this.principalList = []
          return
        } 
        

        const data = await getDepartByComId(newValue)
        this.departmentList = data.data
        if (this.isFirstEdit) {
          return
        }
        // 清空部门，机房输入框
        this.addForm.departmentid = ''
        this.addForm.computerroomid = ''
      }
    },
    // 部门换了，找机房
    "addForm.departmentid": {
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据公司，获得该公司的部门
         if (!newValue){
            // 清空 公司，部门
            this.addForm.computerroomid = ''
            this.roomList = []
             this.addForm.sysuserid = ''
            this.principalList = []

          return
        }

        // 多条件查询机房
        const data = await queryComputerRoom({
          page: {
            current: 1,
            size: 1000
          },
          query: {
            computeRoomName: '',
            companyId: this.addForm.compayid,
            deptId: this.addForm.departmentid,
            areaId: this.queryAreaId(this.addForm.compayid),
            principalName: "" // 接口有需要，但页面中没有输入的地方
          },
        })
        this.roomList = data.data.records
        if (this.isFirstEdit) {
          return
        }
        this.addForm.computerroomid = ''
      }
    },
    "addForm.computerroomid": {
      async handler (newValue, oldValue) {
         if (!newValue){
            // 清空 公司，部门
             this.addForm.sysuserid = ''
            this.principalList = []
            
          return
        }
        // 多条件查询机房

        let room = this.roomList.find(item => {
          return item.id = this.addForm.computerroomid
        })
        // 目前一个机房只有一个管理员，如果将来增加再说。
        this.principalList = [room.sysUser]

      }
    },

    // 公司变化查部门
    "queryForm.query.compayid": {
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据公司，获得该公司的部门
         if (!newValue){
            // 清空 公司，部门
            this.queryForm.query.departmentid = ''
            this.serarch_departmentList = []
            this.queryForm.query.computerroomid = ''
            this.serarch_roomList = []
          return
        } 
        
        const data = await getDepartByComId(newValue)
        console.log(data);
        this.serarch_departmentList = data.data
        if (this.isFirstEdit) {
          return
        }
        // 清空部门，机房输入框
        this.queryForm.query.departmentid = null
        this.queryForm.query.computerroomid = null
      }
    },
    // 部门变化，查机房
    "queryForm.query.departmentid": {
      async handler (newValue, oldValue) {
        console.log(newValue || this.isFirstEdit);
        // 根据公司，获得该公司的部门
         
        if (!newValue){
            // 清空 公司，部门
            this.queryForm.query.computerroomid = ''
            this.serarch_roomList = []
          return
        } 

        // 多条件查询机房
        const data = await queryComputerRoom({
          page: {
            current: 1,
            size: 1000
          },
          query: {
            computeRoomName: '',
            companyId: this.queryForm.query.compayid,
            deptId: this.queryForm.query.departmentid,
            areaId: this.queryAreaId(this.queryForm.query.compayid),
            principalName: "" // 接口有需要，但页面中没有输入的地方
          },
        })
        this.serarch_roomList = data.data.records
        if (this.isFirstEdit) {
          return
        }

        this.queryForm.query.computerroomid = null
      }
    },

  },
  //方法集合",
  methods: {

    checkName () {
      this.$refs.addFormRef.validateField('name')
    },

    // 获得当前选中的公司的地区ID
    queryAreaId (compayid) {
      let c = this.companyList.find(it => {
        return compayid == it.id
      })
      return c.areaId
    },
    search () {
      this.multipleSelection = [];
      this.queryForm.page.current = 1;
      this.init();
    },
    reSet () {
      this.multipleSelection = [];
      this.queryForm = this.$options.data().queryForm;
      this.init();
    },
    async init () {
      const { data } = await getList(this.queryForm);
      console.log(data);
      this.tableData = data.records;
      this.total = data.total
      console.log(this.tableData);
    },
    // 获取公司列表
    async getCompanyList () {
      const data = await getCompanyList();
      console.log(data);
      this.companyList = data.data;
    },
    // 获取部门列表
    // async getDepartmentList () {
    //   const data = await getDepartmentList();
    //   console.log(data.data);
    //   this.departmentList = data.data.data;
    // },
    // 获取机房列表
    async getRoomList () {
      const data = await getRoomList();
      this.roomList = data;
    },
    // 获取供应商列表
    async getSupplierList () {
      const data = await getSupplierList();
      console.log(data);
      this.supplierList = data.data;
    },
    // 获取负责人列表
    // async getPrincipalList () {
    //   const data = await getPrincipalList();
    //   this.principalList = data;
    // },
    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },
    handleCurrentChange (index) {
      this.current = index
      this.init()
    },
    saveCabinet () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        if (this.addForm.id) {

          let ret = await doEdit(this.addForm);

          if (ret.code == 20000) {
            this.$message({
              "type": "success",
              "message": ret.message
            })
          }
        } else {

          let ret = await doAdd(this.addForm);
          if (ret.code == 20000) {
            this.$message({
              "type": "success",
              "message": ret.message
            })
          } else {
            this.$message({
              "type": "warn",
              "message": "添加失败"
            })
          }

        }
        this.addDialogClosed();
        this.init();
      })
    },
    deleteCabinet (row) {
      this.$confirm('此操作将删除该机柜, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async () => {
        let ret = await doDelete([row.id]);

        if (ret.code == 20000) {

          let type = ''
          if (ret.data || ret.message.indexOf('成功') != -1) {
            ret.message = '删除成功'
            type = 'success'
          } else {
            type = 'error'
          }
          this.$message({
            type: type,
            message: ret.message,
          })

          // console.log(this.multipleSelection.length);
          if (this.tableData.length == 1) {
            this.queryForm.page.current = this.queryForm.page.current - 1
            if (this.queryForm.page.current < 1) {
              this.queryForm.page.current = 1
            }
          }

          this.multipleSelection = []
          this.init()


        }


      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    catchDelete () {
      this.$confirm('此操作将删除所选机房, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let list = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            list.push(this.multipleSelection[i].id)
          }
          // for(let i in list){
          //   console.log(list[i])
          // }
          let ret = await doDelete(list)
          console.log(ret, '--------------ret----');

          if (ret.code == 20000) {

            let type = ''
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    editCabinet (row) {
      console.log(row);
      console.log(this.addForm);
      if (row && row.id) {
        this.formTitle = '修改机柜信息';
        this.isFirstEdit = true
        // this.addForm = Object.assign({}, row);
        Object.assign(this.addForm, row)
      } else {
        this.formTitle = '添加机柜';
      }
      this.multipleSelection = [];
      this.addDialogVisible = true;

      setTimeout(() => {
        this.isFirstEdit = false
      }, 2000);
    },
    addDialogClosed () {
      this.addForm = this.$options.data().addForm
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = false

      this.departmentList = []
      this.roomList = []

    }
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate () { },

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created () {
    this.init();
    this.getCompanyList();

    // 要根据公司，找 部门，根据部门，找 机房 
    // this.getDepartmentList();
    // this.getRoomList();
    this.getSupplierList();
    // this.getPrincipalList();
  },

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted () { },
}
</script>

<style lang='scss' scoped>
.el-select {
  width: 100% !important;
}
.el-date-editor.el-input {
  width: 100% !important;
}
</style>